package com.mhy.glide;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toast;

import androidx.annotation.ColorRes;
import androidx.annotation.DrawableRes;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RawRes;
import androidx.annotation.RequiresApi;
import androidx.core.content.ContextCompat;

import com.bumptech.glide.TransitionOptions;
import com.bumptech.glide.load.DataSource;
import com.bumptech.glide.load.MultiTransformation;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.load.engine.GlideException;
import com.bumptech.glide.load.resource.bitmap.CircleCrop;
import com.bumptech.glide.load.resource.bitmap.RoundedCorners;
import com.bumptech.glide.request.RequestListener;
import com.bumptech.glide.request.RequestOptions;
import com.bumptech.glide.request.target.CustomTarget;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.target.Target;
import com.bumptech.glide.request.transition.Transition;
import com.mhy.glide.progress.ProgressInterceptor;
import com.mhy.glide.progress.ProgressListener;
import com.mhy.glide.transform.CornerTransform;
import com.mhy.glide.transform.GlideCircleTransform;
import com.mhy.glide.transform.GlideCircleWithBorder;


import jp.wasabeef.glide.transformations.BlurTransformation;
import jp.wasabeef.glide.transformations.RoundedCornersTransformation;
import pl.droidsonroids.gif.GifDrawable;
import pl.droidsonroids.gif.GifImageView;

import static com.bumptech.glide.request.RequestOptions.bitmapTransform;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.concurrent.ExecutionException;

// 高斯模糊和圆角

/**
 * 类描述：Glide封装实体类
 * 作  者：mahongiyn
 * 时  间：2017-07-11
 * 修改备注：glide 4.9.0 可以直接配置圆形和圆角图片 transforms(new CircleCrop())
 * 渐变设置和监听设置有更改 Drawable
 * asBitmap() 需要设置在 load(url)之前
 * 缓存 ：DiskCacheStrategy.NONE      不缓存
 * 缓存 ：DiskCacheStrategy.RESOURCE  缓存解码后的图
 * 缓存 ：DiskCacheStrategy.DATA      缓存未解码的数据
 * 缓存 ：DiskCacheStrategy.AUTOMATIC 默认选项
 * 缓存 ：DiskCacheStrategy.ALL       对于远程图缓存RESOURCE+DATA，对于本地图缓存RESOURCE
 *
 * @author mahongyin
 */
public class GlideUtil {

    private static int LoadingImg = R.color.colorAccent;
    private static int ErrorImg = R.color.colorPrimary;
    private static int EmptyImg = R.color.colorPrimaryDark;

    /**
     * 设置带进度监听的图片
     */
    public static void showProgressImage(Context context, final String imgUrl, ImageView iv, ProgressListener loadListener) {
        ProgressInterceptor.addListener(imgUrl, loadListener);
        GlideApp.with(context)
                .load(imgUrl)
                .diskCacheStrategy(DiskCacheStrategy.RESOURCE)
                .placeholder(LoadingImg)
                .error(ErrorImg)
                .fallback(EmptyImg)
                .addListener(new RequestListener<Drawable>() {
                    @Override
                    public boolean onLoadFailed(@Nullable GlideException e, Object model, Target<Drawable> target, boolean isFirstResource) {
                        ProgressInterceptor.removeListener(imgUrl);
                        Log.e("onProgress", "加载失败\n" + e.toString());
                        return false;
                    }

                    @Override
                    public boolean onResourceReady(Drawable resource, Object model, Target<Drawable> target, DataSource dataSource, boolean isFirstResource) {
                        ProgressInterceptor.removeListener(imgUrl);
                        Log.e("onProgress:", " 加载成功");
                        return false;
                    }
                })
                .into(iv);
    }

    public static void showImage(Context context, String Url, ImageView iv) {
        GlideApp.with(context)
                .asBitmap() // 不显示gif图
                .load(Url)
                .centerCrop()//裁剪
                .diskCacheStrategy(DiskCacheStrategy.RESOURCE)
                .placeholder(LoadingImg)
                .error(ErrorImg)
                .fallback(EmptyImg)
                .into(iv);
    }

    public static void showGif(Context context, String Url, ImageView iv) {
        GlideApp.with(context)
                .asGifLib() // 显示gif图
                .load(Url)
                .diskCacheStrategy(DiskCacheStrategy.DATA)//缓存
                .placeholder(LoadingImg)
                .error(ErrorImg)
                .into(iv);
    }

    public static void showGif2(InputStream stream, final GifImageView imageView) {
        //file:///android_asset/yourfile
        //android.resource://package_name/raw/yourfile
        try {
            pl.droidsonroids.gif.GifDrawable gifDrawable = new GifDrawable(stream);
//         gifImageView.setBackgroundDrawable(gifDrawable);//虽然过时，但是支持老版本
//         gifImageView.setBackground(gifDrawable);
            imageView.setImageDrawable(gifDrawable);
        } catch (IOException e) {
        }
    }

    public static void showGif2(Context context, String url, final GifImageView imageView) {
        GlideApp.with(context)
                .asFile()
                .load(url)
                .diskCacheStrategy(DiskCacheStrategy.DATA)
                .placeholder(LoadingImg)
                .error(ErrorImg)
                .into(new CustomTarget<File>() {
                    @Override
                    public void onResourceReady(@NonNull File resource, @Nullable Transition<? super File> transition) {
                        try {
                            imageView.setImageDrawable(
                                    new pl.droidsonroids.gif.GifDrawable(resource));
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onLoadCleared(@Nullable Drawable placeholder) {

                    }
                });
    }

    /**
     * 设置圆角图片
     */
    public static void showRoundCornerImg(Context context, String url, ImageView iv, int rudius) {
        GlideApp.with(context)
                .load(url)
                .placeholder(LoadingImg)//占位符 加载中显示  or (new ColorDeawable(Color.BLACK))
                .error(ErrorImg)
                .diskCacheStrategy(DiskCacheStrategy.RESOURCE)//缓存
                .transform(
//                        new GlideRoundTransform(rudius)
                        new RoundedCorners(rudius)  //Glide 4.9
                ).into(iv);
    }

    public static int dip2px(Context context, float dipValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dipValue * scale + 0.5f);
    }

    //绘制上边俩角圆角
    public static void topRoundCornerImg(Context context, String url, ImageView iv, int rudius) {
        CornerTransform transformation = new CornerTransform(context, dip2px(context, rudius));
        //只是绘制左上角和右上角圆角
        transformation.setExceptCorner(false, false, true, true);
        GlideApp.with(context).asBitmap()
                .load(url)
                .transform(transformation)
                .error(ErrorImg)
                .placeholder(LoadingImg)
                .into(iv);
//      Glide4.0+上的使用
//        RequestOptions options = new RequestOptions()
//                .error(ErrorImg)
//                .placeholder(LoadingImg)
//                .transform(transformation);
//        GlideApp.with(context).asBitmap().load(url).apply(options).into(iv);
    }

    /**
     * 设置圆形图片
     * //不带边框的圆形图片
     * GlideApp.with.load.apply(RequestOptions.circleCropTransform()).into;
     */
    public static void showCircleImg(Context context, String url, ImageView iv) {
        GlideApp.with(context)
                .load(url)
                .placeholder(LoadingImg)
                .error(ErrorImg)
                .diskCacheStrategy(DiskCacheStrategy.RESOURCE)
                .transform(
//                        new GlideCircleTransform()
                        new CircleCrop()   //Glide 4.9
                )
                .into(iv);
    }


    //模糊
    public static void showBlurImg(Context context, String url, ImageView iv) {
        GlideApp.with(context)
                .load(url)
                .placeholder(LoadingImg)
                .error(ErrorImg)
                .diskCacheStrategy(DiskCacheStrategy.ALL)//缓存
                .transform(new BlurTransformation(15))
                .into(iv);
    }

    //多重变换
    public static void showMultiImg(Context context, String url, ImageView iv) {
        GlideApp.with(context)
                .load(url)
                .placeholder(LoadingImg)
                .error(ErrorImg)
                .diskCacheStrategy(DiskCacheStrategy.RESOURCE)//缓存
                .transform(new MultiTransformation(new RoundedCornersTransformation(15, 5),
                        new BlurTransformation(15)))
                .into(iv);
    }

    //加载网络图截图用
    public static void sreenImg(Context context, String url, final ImageView iv) {
        GlideApp.with(context)
                .asBitmap().load(url)
                .into(new SimpleTarget<Bitmap>() {
                    @Override
                    public void onResourceReady(@NonNull Bitmap resource, @Nullable Transition<? super Bitmap> transition) {
                        iv.setImageBitmap(resource);
                    }
                });
    }

    // 设置背景
    public static void loadImageBackGround(Context context, String url, final View view) {

        GlideApp.with(context).load(url).diskCacheStrategy(DiskCacheStrategy.ALL).into(
                new SimpleTarget<Drawable>() {
                    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
                    @Override
                    public void onResourceReady(@NonNull Drawable resource, @Nullable Transition<? super Drawable> transition) {
                        view.setBackground(resource);
                    }
                });
    }

    //固定高宽
    public static void showFinalImg(Context context, String url, ImageView iv) {
        GlideApp.with(context)
                .load(url)
                .placeholder(LoadingImg)
                .error(ErrorImg)
                .diskCacheStrategy(DiskCacheStrategy.ALL)//缓存
                .override(100, 100)
                .into(iv);
    }

    //监听器
    public static void showListenerImg(Context context, String url, ImageView iv) {
        GlideApp.with(context)
                .load(url)
                .placeholder(LoadingImg)
                .error(ErrorImg)
                .diskCacheStrategy(DiskCacheStrategy.RESOURCE)
                .listener(new RequestListener<Drawable>() {
                    //加载失败  false 未消费 继续 into(imgview)   // true 已消费  不再走into()
                    @Override
                    public boolean onLoadFailed(@Nullable GlideException e, Object model, Target<Drawable> target, boolean isFirstResource) {
                        return false;
                    }

                    //加载成功  false 未消费 继续 into(imgview)   //true 已消费  不再走into()
                    @Override
                    public boolean onResourceReady(Drawable resource, Object model, Target<Drawable> target, DataSource dataSource, boolean isFirstResource) {
                        return false;
                    }
                })
                .into(iv);
    }

    public static Bitmap downloadBitmap(final Context context, String imageUrl, int width, int height) {
        try {
            Bitmap bitmap = GlideApp.with(context)
                    .asBitmap()
                    .load(imageUrl)
                    .into(width, height)
                    .get();
            return bitmap;
        } catch (ExecutionException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 复制文件
     *
     * @param filename 文件名
     * @param bytes    数据
     */
    public static void copy(String filename, byte[] bytes) {
        try {
            //如果手机已插入sd卡,且app具有读写sd卡的权限
            if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
                FileOutputStream output = null;
                output = new FileOutputStream(filename);
                output.write(bytes);
                output.close();
            } else {
                Log.i("TAG", "copy:fail, " + filename);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 下载图片
     */
    private void downloadIMG(final Context context, final String iconUrl, final File outFile) {
        int myWidth = Target.SIZE_ORIGINAL;
        int myHeight = Target.SIZE_ORIGINAL;
        GlideApp.with(context).asBitmap()
                .load(iconUrl)
                .into(new SimpleTarget<Bitmap>(myWidth, myHeight) {
                    @Override
                    public void onResourceReady(@NonNull Bitmap resource, @Nullable Transition<? super Bitmap> transition) {
                        if (null != resource) {
                            saveIMG(context, resource, outFile);
                        }
                    }

                });
    }

    private void saveIMG(Context context, Bitmap bitmap, File currentFile) {
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(currentFile);
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);//质量为100表示设置压缩率为0
            fos.flush();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (fos != null) {
                    fos.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        // 通知图库更新
        context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE,
                Uri.fromFile(new File(currentFile.getPath()))));
    }

    /***
     *  "https://web-1259617641.cos.ap-nanjing.myqcloud.com/woshidianjiutu.9.png"
     */
    public static void downloadFile(final Context context, String imageUrl, final File outPath) {

        GlideApp.with(context)
                .downloadOnly()
                .load(imageUrl)
                .listener(new RequestListener<File>() {
                    @Override
                    public boolean onLoadFailed(@Nullable GlideException e, Object model, Target<File> target, boolean isFirstResource) {
                        Toast.makeText(context, "下载失败", Toast.LENGTH_SHORT).show();
                        return false;
                    }

                    @Override
                    public boolean onResourceReady(File resource, Object model, Target<File> target, DataSource dataSource, boolean isFirstResource) {
                        Toast.makeText(context, "下载成功", Toast.LENGTH_SHORT).show();
                        Log.e("第三方的速度", "onResourceReady: " + resource);
                        Log.e("第三方的速度", "model: " + model);
                        Log.e("第三方的速度", "model: " + target.toString());
                        Log.e("第三方的速度", "dataSource: " + dataSource);
                        Log.e("第三方的速度", "onResourceReady: " + isFirstResource);
                        //把gilde下载得到图片复制到定义好的目录中去
                        copy(resource, outPath);
                        // 最后通知图库更新
                        context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE,
                                Uri.fromFile(new File(outPath.getPath()))));
                        return false;
                    }
                })
                .preload();
    }

    /**
     * 复制文件
     *
     * @param source 输入文件
     * @param target 输出文件
     */
    public static void copy(File source, File target) {
        FileInputStream fileInputStream = null;
        FileOutputStream fileOutputStream = null;
        try {
            fileInputStream = new FileInputStream(source);
            fileOutputStream = new FileOutputStream(target);
            byte[] buffer = new byte[1024];
            while (fileInputStream.read(buffer) > 0) {
                fileOutputStream.write(buffer);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                fileInputStream.close();
                fileOutputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 带白色边框的圆形图片
     *
     * @param borderColor #2422552
     */
    public static void showCircleWithBorder(Context context, ImageView imageView, String imageUrl, String borderColor) {
        GlideApp.with(context).asBitmap()
                .load(imageUrl)
                .placeholder(LoadingImg)
                .error(ErrorImg)
                .apply(RequestOptions.bitmapTransform(new CircleCrop()))
                .transform(new GlideCircleWithBorder(context, 3, Color.parseColor(borderColor)))
                .into(imageView);
    }

    public static void showCircleWithBorder(Context context, ImageView imageView, @RawRes @DrawableRes @Nullable Integer imageId, String borderColor) {
        GlideApp.with(context).asBitmap()
                .load(imageId)
                .placeholder(LoadingImg)
                .error(ErrorImg)
                .apply(RequestOptions.bitmapTransform(new CircleCrop()))
                .transform(new GlideCircleWithBorder(context, 3, Color.parseColor(
                        borderColor) /*R.color.wriht*//*Color.parseColor("#ffffff")*/))
                .into(imageView);
    }

    public static void showCircleWithBorder(Context context, ImageView imageView, String imageUrl, @ColorRes int borderColor) {
        GlideApp.with(context).asBitmap()
                .load(imageUrl)
                .placeholder(LoadingImg)
                .error(ErrorImg)
                .apply(RequestOptions.bitmapTransform(new CircleCrop()))
                .transform(new GlideCircleWithBorder(context, 3, context.getResources().getColor(
                        borderColor) /*R.color.wriht*//*Color.parseColor("#ffffff")*/))
                .into(imageView);
    }

    public static void showCircleWithBorder(Context context, ImageView imageView, @RawRes @DrawableRes @Nullable Integer imageId, @ColorRes int borderColor) {
        GlideApp.with(context).asBitmap()
                .load(imageId)
                .placeholder(LoadingImg)
                .error(ErrorImg)
                .apply(RequestOptions.bitmapTransform(new CircleCrop()))
                .transform(new GlideCircleWithBorder(context, 3, ContextCompat.getColor(context,
                        borderColor) /*R.color.wriht*//*Color.parseColor("#ffffff")*/))
                .into(imageView);
    }

    /**
     * 内存缓存清理（主线程）
     */
    public static void clearMemoryCache(Context context) {
        GlideApp.get(context).clearMemory();
    }

    /**
     * 磁盘缓存清理（子线程）
     */
    public static void clearFileCache(final Context context) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                GlideApp.get(context).clearDiskCache();
            }
        }).start();
    }
}
